<?php  # Script -- broadcast.php

/* Author @ Huoty
 *   Date @ 2015-11-16 10:53:47
 *  Brief @ 
 */

/* ip地址转换广播地址:
 * 	（1）IP地址与子网掩码进行“位与”运算，得到网络地址
 * 	（2）子网掩码“取反”运算，然后与网络地址进行“位或”运算，得到广播地址
 */
function ip2broadcast($ip,$mask){

	$ipSplit = explode('.',$ip);
	$maskSplit = explode('.',$mask);
	$broadcast = null;
	for ($i=0; $i < 4; $i++) {
		$ipBin = sprintf("%b",$ipSplit[$i]);
		while((8-strlen($ipBin))>0) $ipBin = "0".$ipBin;

		$maskBin = sprintf("%b",$maskSplit[$i]);
		while((8-strlen($maskBin))>0) $maskBin = "0".$maskBin;

		$broadcastBin = null;
		for ($j=0; $j < 8; $j++) { 
			$broadcastBin .= (!intval(substr($maskBin, $j , 1))) |
						(intval(substr($ipBin, $j , 1)) & intval(substr($maskBin, $j , 1)));
		}

		if ($i>0) $broadcast .= ".";
		$broadcast .= bindec($broadcastBin);
	}
	return $broadcast;
}

echo ip2broadcast("192.168.12.18", "255.255.255.0");

?>
